import { Component } from "react"
import src from './images/avatar.png'
import { formatTime } from './utils'
import './styles/index.css'
import Tab from './components/Tab'
import CommentList from "./components/CommentList"
import Form from "./components/Form"
class App extends Component {
  state = {
    // hot: 热度排序  time: 时间排序
    tabs: [
      {
        id: 1,
        name: '热度',
        type: 'hot'
      },
      {
        id: 2,
        name: '时间',
        type: 'time'
      }
    ],
    content: '',
    active: 'hot',
    list: [
      {
        id: 1,
        author: '刘德华',
        comment: '给我一杯忘情水',
        time: new Date('2021-10-10 09:09:00'),
        // 1: 点赞 0：无态度 -1:踩
        attitude: 1,
        imgsrc: '/刘德华.png'
      },
      {
        id: 2,
        author: '周杰伦',
        comment: '哎哟，不错哦',
        time: new Date('2021-10-11 09:09:00'),
        // 1: 点赞 0：无态度 -1:踩
        attitude: 0,
        imgsrc: '/周杰伦.png'
      },
      {
        id: 3,
        author: '五月天',
        comment: '不打扰，是我的温柔',
        time: new Date('2021-10-11 10:09:00'),
        // 1: 点赞 0：无态度 -1:踩
        attitude: -1,
        imgsrc: '/五月天.png'
      }
    ]
  }
  changeTab = (type) => {
    this.setState({
      active: type
    })
  }
  del = (id) => {
    let newList = this.state.list.filter((item, index, array) => { return item.id !== id })
    this.setState({
      list: newList
    })
  }
  changeAttitude = (id, attitude) => {
    this.setState({
      list: this.state.list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            attitude,
          }
        } else {
          return item
        }
      }),
    })
  }
  addComment = (text) => {
    const newCom = {
      id: Date.now(),
      author: '作者',
      comment: text,
      time: new Date(),
      // 1: 点赞 0：无态度 -1:踩
      attitude: 0,
      imgsrc: '/avatar.png'
    }
    this.setState({
      list: [newCom, ...this.state.list],
      // content: ''
    })
    // console.dir(document.querySelector('.ipt-txt'))

  }
  render () {
    return (
      <div className="App">
        <div className="comment-container">
          {/* 评论数 */}
          <div className="comment-head">
            <span>{this.state.list.length} 评论</span>
          </div>
          {/* 排序 */}
          <Tab tabs={this.state.tabs}
            changeTab={this.changeTab}
            active={this.state.active}></Tab>
          <Form addComment={this.addComment}></Form>
          {/* 添加评论 */}
          <CommentList list={this.state.list} del={this.del} changeAttitude={this.changeAttitude}></CommentList>
          {/* 评论列表 */}
        </div>
      </div >
    )
  }
  componentDidUpdate () {
    localStorage.setItem('list', JSON.stringify(this.state.list))
  }

  componentDidMount () {
    const list = JSON.parse(localStorage.getItem('list'))
    this.setState({ list })
  }
}
export default App